//
//  GSStrategyDetailViewController.m
//  GameSky
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSStrategyDetailViewController.h"
#import "GSArticleViewController.h"
#import "GSSearchViewController.h"
#import "GSNewsMainCell.h"
#import "GSStrategyDetailCell.h"
#import "GSStrategyHeaderView.h"

@interface GSStrategyDetailViewController () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) GSStrategyHeaderView *headerView;

@property (nonatomic, strong) NSMutableArray *listDataArray;
@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) FMDatabase *db;// 数据库

@end

@implementation GSStrategyDetailViewController

- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = [NSMutableArray array];
    }
    return _listDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    // 配置model属性初始值;
    _pageIndex = 1;
    
    [self addTableView];
    [self loadData];
    [self refreshData];
    [self setupSubscribeData];
    [self addNavigationBar];
    
}
/**
 *  数据加载
 */
- (void)loadData
{
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    paraDict[@"request"] = @{@"parentNodeId":@"strategy", @"nodeIds":_model.specialID, @"pageIndex":@(_pageIndex), @"elementsCountPerPage":@"20"};
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/AllChannelList" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        if (data) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSArray *resultArray = dataDict[@"result"];
            
            if (_pageIndex == 1) {
                [self.listDataArray removeAllObjects];
            }
            
            for (NSDictionary *subDict in resultArray) {
                GSNewsListModel *model = [[GSNewsListModel alloc] init];
                [model setValuesForKeysWithDictionary:subDict];
                [self.listDataArray addObject:model];
            }
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            
            // 刷新界面;
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

/**
 *  获得订阅信息
 */
- (void)setupSubscribeData
{
    NSMutableArray *dataArray = [[GSDataBaseManager sharedDataBase] subscribeDataFromDataBase];
    NSString *specialID = [NSString stringWithFormat:@"%@",_model.specialID];
    for (GSSubscrebe_Add_Topic *model in dataArray) {
        if ([model.sourceId isEqualToString:specialID]) {
            _model.isSubscribed = YES;
        } else {
            _model.isSubscribed = NO;
        }
    }
}

/**
 *  数据刷新
 */
- (void)refreshData
{
    // 下拉刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新重新加载数据;
        _pageIndex = 1;
        [self loadData];
    }];
    
    // 上拉刷新
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 上拉刷新依次叠加数据;
        _pageIndex += 1;
        [self loadData];
    }];
}

// 添加TableView;
- (void)addTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight - 20)];
    // 夜间模式
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 100;
    _headerView = [[GSStrategyHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    [_headerView.searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.tableView.tableHeaderView = _headerView;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[GSNewsMainCell class] forCellReuseIdentifier:@"GSNewsMainCell"];
    [self.tableView registerClass:[GSStrategyDetailCell class] forCellReuseIdentifier:@"GSStrategyDetailCell"];
}

- (void)searchBtnClick:(UIButton *)button
{    
    UINavigationController *naviC = [[UINavigationController alloc] initWithRootViewController:[[GSSearchViewController alloc] init]];
    [self presentViewController:naviC animated:YES completion:nil];
}

// 添加自定义导航栏;
- (void)addNavigationBar
{
    GSCustomNavigationBar *navBar = [[GSCustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    [self.view addSubview:navBar];
    // 左侧按钮
    [navBar.leftButton setImage:[UIImage imageNamed:@"common_Icon_Back_20x20_UIMode_Day"] forState:(UIControlStateNormal)];
    [navBar.leftButton addTarget:self action:@selector(leftBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];    
    
    // 右侧按钮
    navBar.rightButton.selected = _model.isSubscribed;
    [navBar.rightButton setImage:[UIImage imageNamed:@"common_Icon_SubscribeButtonNormal_54x26_UIMode_Day"] forState:(UIControlStateNormal)];
    [navBar.rightButton setImage:[UIImage imageNamed:@"common_Icon_SubscribeButtonSelected_54x26_UIMode_Day"] forState:(UIControlStateSelected)];
    [navBar.rightButton addTarget:self action:@selector(rightBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 中间标题
    navBar.titleLabel.text = self.model.title;
}
- (void)leftBtnClick:(UIButton *)button
{
    // 显示标签栏;
    self.tabBarController.tabBar.hidden = NO;
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightBtnClick:(UIButton *)button
{
    button.selected = !button.selected;
    _model.isSubscribed = button.selected;
    // 获得数据库并处理数据;
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *dataPath = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:dataPath];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }
    NSString *specialID = [NSString stringWithFormat:@"%@",_model.specialID];
    NSData *data = UIImagePNGRepresentation(_model.image);
    if (button.selected) {
        // 插入数据
        if (![_db executeUpdate:@"insert into SubscribeList(nodeIds,cnt,sourceName,imageData) values(?,?,?,?)", specialID, _model.favoriteCnt, _model.title, data]) {
            NSLog(@"插入数据失败");
        }
    } else {
        // 删除数据
        if (![_db executeUpdate:@"delete from SubscribeList where nodeIds = ?",specialID]) {
            NSLog(@"删除数据失败");
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GSNewsListModel *model = self.listDataArray[indexPath.row];
    if (model.thumbnailURLsArray.count) {
        GSNewsMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSNewsMainCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    } else {
        GSStrategyDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSStrategyDetailCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GSArticleViewController *articleDVC = [[GSArticleViewController alloc] init];
    articleDVC.contentID = [self.listDataArray[indexPath.row] contentId];
    [self.navigationController pushViewController:articleDVC animated:YES];
}

/**
 *  根据ScrollView纵向偏移量弹出搜索框;
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -22 && scrollView.contentOffset.y > -44)
    {
        [scrollView setContentOffset:CGPointMake(0, -44)];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
